<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="clearSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-btn-auth="'park:enterprise:add_edit'" type="primary" @click="$router.push('/addEnterprise')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange">
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态">
                <template #default="scope">
                  <!--
                    差值表达式支持函数调用吗？支持
                    调用一个函数的时候 差值表达式的位置渲染的是什么？ 函数执行之后的返回值
                   -->
                  <el-tag :type="formatInfoType(scope.row.status)"> {{ formatStatus(scope.row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <!--
                  退租：如果当前是退租的状态 禁用  如果不是退租的状态 启用
                  删除：只有已退租的时候 删除才是启用的 否则就是禁用的
                 -->
                <template #default="scope">
                  <el-button v-btn-auth="'park:rent:add_surrender'" size="mini" :disabled="scope.row.status === 3" type="text" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button v-btn-auth="'park:rent:add_surrender'" size="mini" :disabled="scope.row.status !== 3" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button v-btn-auth="'park:rent:add_surrender'" size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button v-btn-auth="'park:enterprise:query'" size="mini" type="text" @click="lookRent(scope.row.id)">查看</el-button>
            <el-button v-btn-auth="'park:enterprise:add_edit'" size="mini" type="text" @click="editEnterprise(scope.row.id)">编辑</el-button>
            <el-button v-btn-auth="'park:enterprise:remove'" size="mini" type="text" @click="delEnterprise(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="sizes, total, prev, pager, next"
        :total="total"
        :page-sizes="[2, 5, 10]"
        :page-size="params.pageSize"
        @current-change="pageChange"
        @size-change="sizeChange"
      />
    </div>

    <!-- 添加合同弹框 -->
    <el-dialog
      title="添加合同"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
      @open="openDialog"
    >
      <!-- 默认插槽 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <!--
              上传实现流程：
                1. el-upload 打开本地文件 并且校验这个文件是否符合要求 - File
                2. :http-request = 'upload'
                3. 按照接口的要求格式 得到类型为FormData的对象  new FormData()
                4. 按照要求往formData中添加字段数据 fd.append('字段名', '字段值')
                5. 调用上传接口
                6. 拿到返回的文件地址和其他有用的信息id 存入data中的响应式数据的位置 将来提交表单
             -->
            <el-upload
              ref="uploadRef"
              action="#"
              :limit="1"
              :http-request="upload"
              :on-remove="remove"
              @before-upload="beforeUpload"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getListAPI, addRentAPI, getRentListAPI, outRentAPI, deleteEnterpriseAPI } from '@/api/park'
import { getBuildingRentListAPI } from '@/api/building'
import { uploadAPI } from '@/api/common'
import { mapState } from 'vuex'

export default {
  data() {
    return {
      list: [], // 企业列表
      params: {
        name: '',
        page: 1,
        pageSize: 2
      },
      total: 0,
      dialogVisible: false, // 添加合同弹窗
      rentForm: { // 添加合同表单
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      buildingList: [] // 楼宇列表
    }
  },
  computed: {
    ...mapState('menu', ['permission'])
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    async getList() {
      // 1. 接口调用
      const res = await getListAPI(this.params)
      // 2. 数据赋值(针对于每一行数据初始化一个专门存放合同列表的位置)
      this.list = res.data.rows.map(item => {
        return {
          ...item,
          rentList: [] // 合同列表
        }
      })
      this.total = res.data.total
    },
    // 页数变化
    pageChange(page) {
      this.params.page = page
      this.getList()
    },
    // 每页条数变化
    sizeChange(val) {
      this.params.pageSize = val
      this.getList()
    },
    // 自定义序号
    indexMethod(index) {
      return this.params.pageSize * (this.params.page - 1) + index + 1
    },
    // 查询
    doSearch() {
      this.params.page = 1
      this.getList()
    },
    // 列表展开
    async onExpandChange(row, expanded) {
      // 判断当前是展开还是关闭
      const isInclude = expanded.find(item => item.id === row.id)
      if (!isInclude) return
      const res = await getRentListAPI(row.id)
      // eslint-disable-next-line require-atomic-updates
      row.rentList = res.data || []
    },
    clearSearch() {
      console.log('清空了')
      this.getList()
    },
    // 添加合同
    addRent(id) {
      this.dialogVisible = true
      // 把企业id存入表单对象
      this.rentForm.enterpriseId = id
    },
    // 确定添加合同
    confirmAdd() {
      // 1. 表单校验
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // TODO API
          // 2. 调用接口
          // 处理参数
          const { buildingId, contractId, contractUrl, type, enterpriseId } = this.rentForm
          const reqData = {
            buildingId, contractId, contractUrl, type, enterpriseId,
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1]
          }
          addRentAPI(reqData)
          // 1. 弹框关闭
          this.dialogVisible = false
          // 2. 重置一下数据( resetFileds + 手动清除)
          this.$refs.addForm.resetFields()
          this.rentForm = {
            buildingId: null, // 楼宇id
            contractId: null, // 合同id
            contractUrl: '', // 合同Url
            enterpriseId: null, // 企业名称
            type: 0, // 合同类型
            rentTime: [] // 合同时间
          }
          this.$refs.uploadRef.clearFiles()
          this.$message.success('添加成功')
          // 3. 重新拉取一下列表
        }
      })
    },
    // 上传前
    beforeUpload(file) {
      const fileType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      if (!fileType.includes(file.type)) {
        this.$message.error('上传合同文件只能是 PDF、DOC、DOCX 格式!')
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传合同文件大小不能超过5MB!')
        return false
      }
      return true
    },
    // 上传合同
    async upload(res) {
      console.log(res)
      // 1. 把file对象存下来
      const file = res.file
      // 2. 处理formData
      const fd = new FormData()
      fd.append('file', file)
      fd.append('type', 'contract')
      // 3. 调用上传接口
      const _res = await uploadAPI(fd)
      // 4. 存入表单
      this.rentForm.contractId = _res.data.id
      this.rentForm.contractUrl = _res.data.url
    },
    // 移除合同
    remove() {
      this.rentForm.contractId = ''
      this.rentForm.contractUrl = ''
      this.$refs.addForm.validateField('contractId')
    },
    closeDialog() {
      this.dialogVisible = false
    },
    openDialog() {
      this.getBuildList()
    },
    // 获取楼宇下拉列表
    async getBuildList() {
      // 作为下拉列表
      // 1. 单独的接口
      // 2. 使用table列表的接口 - {page:1,pageSize:100}
      const res = await getBuildingRentListAPI()
      this.buildingList = res.data
    },
    // 查看详情
    lookRent(id) {
      this.$router.push(`/enterpriseDetail/${id}`)
    },
    // 编辑
    editEnterprise(id) {
      this.$router.push({
        path: '/addEnterprise',
        query: {
          id
        }
      })
    },
    // 删除
    delEnterprise(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 确定
        await deleteEnterpriseAPI(id)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page--
        }
        this.getList()
      })
    },
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    formatStatus(status) {
      const MAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 退租
    async outRent(id) {
      try {
        await this.$confirm('确定要退租吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await outRentAPI(id)
        this.$message.success('退租成功')
      } catch (error) {
        this.$message.info('已取消')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
